package org.example.jwt1.config;

import org.example.jwt1.handler.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class WebSecurityConfig {
    @Autowired
    RestAuthenticationEntryPoint restAuthenticationEntryPoint;
    @Autowired
    UserDetailsService userDetailsService;
    @Autowired
    JwtLoginSuccessHandler jwtLoginSuccessHandler;
    @Autowired
    JwtLoginFailureHandler jwtLoginFailureHandler;
    @Autowired
    MyAccessDeniedHandler myAccessDeniedHandler;

    @Bean
    SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
        JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter = new JwtAuthenticationTokenFilter();
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        http.authorizeHttpRequests(
                authorize -> authorize
                        .requestMatchers("/toLogin","/login.html").permitAll()
                        .anyRequest().authenticated()

        );
        http.formLogin(
                form -> form
                        .loginProcessingUrl("/doLogin")
                        .successHandler(jwtLoginSuccessHandler)
                        .failureHandler(jwtLoginFailureHandler)
                        .permitAll()

        );
        http.headers(
                headers -> headers.frameOptions(
                        frameOptions -> frameOptions.sameOrigin()
                )
        );

        http.csrf(
                csrf -> csrf.disable()
        );
        http.sessionManagement(
                session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        );
        http.httpBasic(
                httpBasic -> httpBasic.authenticationEntryPoint(restAuthenticationEntryPoint)
        );
        http.userDetailsService(userDetailsService);

        return http.build();
    }
    @Bean
    public WebSecurityCustomizer webSecurityCustomizer(){
        return web -> web.ignoring().requestMatchers("/login.html","/js/**", "/css/**", "/images/**", "/fonts/**");
    }


}
